<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="排序依据" prop="sortField">
        <el-select
          v-model="queryParams.sortField"
          placeholder="排序依据"
          clearable
          style="width: 240px">
          <el-option
            v-for="dict in dict.type.sort_field"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序方式" prop="sortType">
        <el-select
          v-model="queryParams.sortType"
          placeholder="排序方式"
          clearable
          style="width: 240px">
          <el-option
            v-for="dict in dict.type.sort_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList">
<!--      <el-table-column label="序号" fixed align="center" width="80">-->
<!--        <template scope="scope">-->
<!--          <span>{{(queryParams.pageIndex-1)*queryParams.pageSize+(scope.$index + 1)}} </span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="卡片编号" align="center" prop="cardId"/>
      <el-table-column label="卡片名称" align="center" prop="cardName"/>
      <el-table-column label="户主姓名" align="center" prop="useName" />
      <el-table-column label="手机号码" align="center" prop="tel" />
      <el-table-column label="车位数量" align="center" prop="lotCount" />
      <el-table-column label="未过期车位数" align="center" prop="validCount" />
      <el-table-column label="车牌号" align="center" prop="fullCarNoStr" />
      <el-table-column label="审核状态" align="center" prop="cardState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.audit_state" :value="scope.row.cardState"/>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastUpdateTime,'{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRecharge(scope.row)"
          >充值</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageIndex"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" v-model="form"label-width="80px">
        <el-divider>基本信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="卡片名称">
              <el-input v-model="form.cardInfo.cardName" placeholder="请输入卡片名称" :minlength="1" :maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车主姓名">
              <el-input v-model="form.cardInfo.useName" placeholder="请输入车主姓名" :minlength="2" :maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话">
              <el-input v-model="form.cardInfo.tel" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="辅助信息">
              <el-input v-model="form.cardInfo.assist" placeholder="辅助信息" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系地址">
              <el-input v-model="form.cardInfo.contact" placeholder="联系地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门牌号码">
              <el-input v-model="form.cardInfo.roomId" placeholder="门牌号码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注信息">
              <el-input type="textarea" v-model="form.cardInfo.remak" :autosize="{ minRows: 3, maxRows: 5}" placeholder="备注信息" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider>内部车信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="车牌类型">
              <el-select v-model="form.cardInfo.carType" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in dict.type.car_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="8">-->
<!--            <el-form-item label="充值规则">-->
<!--              <el-select v-model="form.cardInfo.ruleId" placeholder="请选择" clearable>-->
<!--                <el-option-->
<!--                  v-for="dict in ruleList"-->
<!--                  :key="dict.ruleId"-->
<!--                  :label="dict.ruleName"-->
<!--                  :value="dict.ruleId"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
      </el-form>

      <el-divider>车位信息</el-divider>
      <el-row :gutter="10" class="mb8">
        <el-col :span="2">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddCarLot"
          >添加</el-button>
        </el-col>
      </el-row>
      <el-table :data="carLotList" tooltip-effect="dark" size="small" ref="table">
        <el-table-column label="可停区域" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.areaId" placeholder="请选择" multiple>
              <el-option
                v-for="dict in spaceList"
                :key="dict.areaCode"
                :label="dict.areaName"
                :value="dict.areaCode"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="车位数量" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.lotCount" oninput="value=value.replace(/[^\d]/g,'')" type="number"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="车位名称" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.lotName" placeholder="车位名称"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteCarLot(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-divider>车牌绑定</el-divider>
      <el-row :gutter="10" class="mb8">
        <el-col :span="2">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddPlateNo"
          >添加</el-button>
        </el-col>
      </el-row>
      <el-table :data="plateNoInfo" tooltip-effect="dark" size="small" ref="table">
        <el-table-column label="车牌号码" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.plateNo" placeholder="车牌号码"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="进出凭据（ETC号/卡号/扫码）" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.etcNo"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeletePlateNo(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 充值对话框 -->
    <el-dialog :title="title" :visible.sync="open2" width="500px" append-to-body>
      <el-form ref="rechargeForm" v-model="rechargeForm"label-width="80px">
        <el-row>
          <el-col :span="22">
            <el-form-item label="车牌类型">
              <el-input v-model="rechargeForm.carTypeName" placeholder="请输入车主姓名" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="22" v-show="false">
            <el-form-item label="车牌类型">
              <el-input v-model="rechargeForm.carType"/>
            </el-form-item>
          </el-col>
<!--          <el-col :span="22">-->
<!--            <el-form-item label="充值规则">-->
<!--              <el-select v-model="rechargeForm.ruleId" placeholder="请选择" clearable>-->
<!--                <el-option-->
<!--                  v-for="dict in ruleList"-->
<!--                  :key="dict.ruleId"-->
<!--                  :label="dict.ruleName"-->
<!--                  :value="dict.ruleId"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="充值选择">
              <el-radio :label="1" v-model="rechargeForm.chargeMethod" @change="changeTitle">按月</el-radio>
              <el-radio :label="2" v-model="rechargeForm.chargeMethod" @change="changeTitle">按天</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item :label="methodTitle">
              <el-input v-model="rechargeForm.chargeNumber" placeholder="请输入" oninput="value=value.replace(/[^\d]/g,'')" type="number"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item :label="numberTitle">
              <el-input v-model="rechargeForm.freeNumber" placeholder="请输入" oninput="value=value.replace(/[^\d]/g,'')" type="number"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="有效时间">
              <el-date-picker
                v-model="dateRange"
                value-format="yyyy-MM-dd"
                style="width:340px"
                type="daterange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="handleTimestamp"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="支付方式">
              <el-select v-model="rechargeForm.payChannel" placeholder="请选择" clearable style="width:340px">
                <el-option
                  v-for="dict in dict.type.pay_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="支付金额">
              <el-input v-model="rechargeForm.amount" placeholder="请输入" oninput="value=value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')" type="number"/>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="充值备注">
              <el-input v-model="rechargeForm.remark" placeholder="请输入" type="textarea" :maxlength="500" :autosize="{ minRows: 5, maxRows: 10}"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { clientUrl } from "@/api/client";
  import { getUserProfile } from "@/api/system/user";

  export default {
    name: "index",
    dicts: ['sort_field', 'sort_type','audit_state','car_type','pay_type'],
    data(){
      return{
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        open2: false,
        // 表单参数
        form: {
          url:'',
          serviceCode:'',
          userId:'',
          userName:'',
          cardInfo:{
            cardId:'',
            cardName:'',
            useName:'',
            tel:'',
            roomId:'',
            remak:'',
            contact:'',
            assist:'',
            carType:'',
            //ruleId:'',
          },
          carLotList:'',
          plateNoInfo:'',
        },
        user:{},
        carLotList:[],
        plateNoInfo:[],

        //列表
        dataList:[],
        // 总条数
        total: 0,
        // 查询参数
        queryParams: {
          url:'/api/wec/GetCarCardList',
          pageIndex: 1,
          pageSize: 10,
          serviceCode: 'getCarCardList',
          sortField:'1',
          sortType:'1',
        },

        getCarInfoParams:{
          url:'/api/wec/GetCarCardInfo',
          serviceCode:'getCarCardInfo',
          cardId:'',
        },

        delParams:{
          url:'/api/wec/DelCarCardInfo',
          serviceCode:'delCarCardInfo',
          cardId:'',
        },

        spaceList:[],
        spaceParams:{
          url:'/api/wec/GetParkingPlaceArea',
          serviceCode: 'getParkingPlaceArea',
        },

        ruleList:[],
        ruleParams:{
          url:'/api/wec/GetCarCardRule',
          serviceCode: 'getCarCardRule',
        },

        auditParams:{
          url:'/api/wec/AuditCardRecharge',
          serviceCode: 'auditCardRecharge',
          auditType: '1',
          cardId: '',
          userId:'',
          userName:'',
          auditStatus: '1',
          auditRemark: '内部车辆',
        },

        methodTitle:'充值月数',
        numberTitle:'赠送月数',
        // 日期范围
        dateRange:[],
        rechargeForm:{},

      }
    },

    created() {
        this.getList();
        this.getSpaceList();
        this.getRuleList();
        this.getUser();
    },

    methods:{
      /** 查询列表 */
      getList() {
        this.loading = true;
        clientUrl(this.queryParams).then(response => {
          let data = JSON.parse(response.data.data)
          this.dataList = data.carCardList;
          this.total = parseInt(data.totalCount);
          this.loading = false;
        });
      },

      /** 获取用户信息 */
      getUser() {
        getUserProfile().then(response => {
          this.user = response.data;
        });
      },

      /** 获取车场空间列表 */
      getSpaceList(){
        clientUrl(this.spaceParams).then(response => {
          let data = JSON.parse(response.data.data)
          this.spaceList = data.areaInfo;
          this.spaceList.push({
            areaCode:-1,
            areaName:"所有区域"
          })
        });
      },

      /** 获取充值规则列表 */
      getRuleList(){
        clientUrl(this.ruleParams).then(response => {
          let data = JSON.parse(response.data.data)
          this.ruleList = data.ruleList;
        });
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageIndex = 1;
        this.getList();
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.queryParams.sortField = '';
        this.queryParams.sortType = '';
        this.handleQuery();
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.cardId)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },

      // 表单重置
      reset() {
        this.form = {
          url:'',
          serviceCode:'',
          userId:'',
          userName:'',
          cardInfo:{
            cardId:'',
            useName:'',
            tel:'',
            roomId:'',
            remak:'',
            contact:'',
            assist:'',
            carType:'',
            //ruleId:'',
          },
          carLotList:'',
          plateNoInfo:'',
        },
        this.carLotList = [],
        this.plateNoInfo = [],
        this.handleAddCarLot();
        this.handleAddPlateNo();
        this.resetForm("form");
      },

      //表单新增
      handleAddCarLot(){
        let length = this.carLotList.length
        this.carLotList.push({
          sequence:length+1,
          areaId:[],
          lotCount:1,
          lotName:'',
        })
      },

      handleAddPlateNo(){
        this.plateNoInfo.push({
          plateNo:'',
          etcNo:'',
        })
      },

      handleDeleteCarLot(row){
        let index = this.carLotList.indexOf(row);
        this.carLotList.splice(index,1);
      },

      handleDeletePlateNo(row){
        let index = this.plateNoInfo.indexOf(row);
        this.plateNoInfo.splice(index,1);
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "新增内部车";
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.getCarInfoParams.cardId = row.cardId;
        clientUrl(this.getCarInfoParams).then(response => {
          let data = JSON.parse(response.data.data)
          this.form.cardInfo.cardId = data.cardId;
          this.form.cardInfo.cardName = data.cardName;
          this.form.cardInfo.useName = data.useName;
          this.form.cardInfo.tel = data.tel;
          this.form.cardInfo.roomId = data.roomId;
          this.form.cardInfo.remak = data.remak;
          this.form.cardInfo.contact = data.contact;
          this.form.cardInfo.assist = data.assist;
          this.carLotList = JSON.parse(data.carLotList);
          this.carLotList.forEach(item=>{
            item.carType =  JSON.stringify(item.carType);
            this.form.cardInfo.carType = item.carType
            //this.form.cardInfo.ruleId = item.ruleId
            item.areaId = item.areaId.split(",").map(Number);
          });
          this.plateNoInfo = JSON.parse(data.plateNoInfo);
          this.form.carLotList =  JSON.stringify(this.carLotList);
          this.form.plateNoInfo = JSON.stringify(this.plateNoInfo);
          this.open = true;
          this.title = "修改内部车";
        });
      },

      submitForm(){
        if(this.form.cardInfo.cardId != ''){
          this.form.url = '/api/wec/ModifyCarCardNo';
          this.form.serviceCode = 'modifyCarCardNo';
        }else{
          this.form.url = '/api/wec/AddCarCardNo';
          this.form.serviceCode = 'addCarCardNo';
        }
        this.form.userId = this.user.userId;
        this.form.userName = this.user.userName;
        this.carLotList.forEach(item=>{
          item.carType = this.form.cardInfo.carType
        });
        this.form.carLotList =  JSON.stringify(this.carLotList);
        this.form.plateNoInfo = JSON.stringify(this.plateNoInfo);


        if(this.form.cardInfo.useName == ''){
          this.$modal.msgError("请输入车主姓名");
          return false;
        }

        clientUrl(this.form).then(response => {
          if(response.data.resMsg == '成功'){
            let data = JSON.parse(response.data.data)
            console.log(data)
            this.auditParams.cardId = data.cardId
            this.auditParams.userId = this.user.userId;
            this.auditParams.userName = this.user.userName;
            clientUrl(this.auditParams).then(res => {
              this.$modal.msgSuccess(res.data.resMsg);
            })
            this.reset();
            this.open = false;
            this.getList();
          }else{
            this.$modal.msgError(response.data.resMsg);
          }
        });
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        this.delParams.cardId = row.cardId;
        this.$modal.confirm('是否确认删除？').
        then(() => {
          clientUrl(this.delParams).then(response => {
            this.getList();
            this.$modal.msgSuccess(response.data.resMsg);
          });
        });
      },

      changeTitle(){
        if(this.rechargeForm.chargeMethod == 1){
          this.methodTitle = '充值月数';
          this.numberTitle = '赠送月数';
        }else if(this.rechargeForm.chargeMethod == 2){
          this.methodTitle = '充值天数';
          this.numberTitle = '赠送天数';
        }
      },

      handleTimestamp(){
        this.rechargeForm.validFrom = undefined;
        this.rechargeForm.validTo = undefined;
        if(this.dateRange)this.rechargeForm.validFrom = this.appendFix(this.dateRange[0],1);
        if(this.dateRange)this.rechargeForm.validTo =  this.appendFix(this.dateRange[1],2);
      },

      handleRecharge(row){
        this.title = "充值";
        this.rechargeForm.url = '/api/wec/PayCarCardFee';
        this.rechargeForm.serviceCode = 'payCarCardFee';
        this.rechargeForm.cardId = row.cardId;
        this.rechargeForm.userId = this.user.userId;
        this.rechargeForm.userName = this.user.userName;
        JSON.parse(row.carLotList).forEach(item=>{
          this.rechargeForm.carType = item.carType
          this.rechargeForm.carTypeName = item.carTypeName
        })
        this.rechargeForm.chargeMethod = 1
        this.open2 = true;
      },

      reset2() {
        this.rechargeForm = {};
        this.resetForm("rechargeForm");
      },

      submitForm2(){
        this.rechargeForm.createTime = this.parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}')
        this.rechargeForm.orderNo = 'P'+new Date().getTime()
        clientUrl(this.rechargeForm).then(response => {
          if(response.data.resMsg == '成功'){
            this.$modal.msgSuccess(response.data.resMsg);
            this.reset2();
            this.open2 = false;
            this.getList();
          }else{
            this.$modal.msgError(response.data.resMsg);
          }
        });
      },

      // 取消按钮
      cancel2() {
        this.open2 = false;
        this.reset2();
      },
    }
  }
</script>

<style scoped>

</style>
